import { stringify } from 'querystring';
import { history } from 'umi';
import { accountLogin,getCropByDomain } from '@/services/login';
import {getUserPermissions} from '@/services/permission';
import { setAuthority,removeAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { queryCodeAll } from '@/services/dataDict';
import {setDictCode} from '@/utils/DataDictUtils';
import {message} from 'antd';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      console.log("login.login",response);
      let success = response.errorCode?false:true;
      if(success){
        //获取用户权限
        // const resp = yield call(getUserPermissions, response.returnValue.appid,response.returnValue.uid);
        // let permissArr=[];
        // if (resp && resp instanceof Array && resp.length > 0) {
        //   permissArr = resp.map((value)=>{return value.permissionCode;});
        // }
        let permissArr=['BASIC_ENTERPRISE','BASIC_CUSTOMER','BASIC_REGION','BASIC_EMPLOYEE','DEVICE_MANAGE','DEVICE_SCENE','CUSTOMER_LOOKAFTER','CUSTOMER_LIVING','CUSTOMER_SLEEP','BEDROOM_SAFE'];
        let resp={
            token:response,
            status:1,
            type:1
        }
        yield put({
          type: 'changeLoginStatus',
          payload: {...resp, status:'ok',type:'client',permissions:permissArr},
        }); 
        
        // yield put({
        //   type:'fetchDict',
        // });

        // Login successfully
        if (success) {
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;

          if (redirect) {
            const redirectUrlParams = new URL(redirect);

            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);

              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              window.location.href = '/';
              return;
            }
          }

          history.replace(redirect || '/');
        }
     }else{
      message.warn(response.errorMessage);
     }
    },
    *fetchDict(_, { call, put }) {
      const response = yield call(queryCodeAll);
      if(response.success){
          setDictCode(response.data);
      }
    },
    *domain({domain,callback}, { call, put }) {
      const response = yield call(getCropByDomain,domain);
      if(callback){
        callback(response);
      }
    },
    *logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      removeAuthority();
      if (window.location.pathname !== '/user/login' && !redirect) {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            // redirect: window.location.href,
            domain:localStorage.getItem('x-yscloud-saas-domain')
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload);
      sessionStorage.setItem("token",payload.token);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
